#include "FileLineEdit.h"

FileLineEdit::FileLineEdit(QWidget *parent)
    : QLineEdit{parent},m_strFilePath("")
{
    m_fileTypes.clear();
    m_fileTypes = QStringList{"*.*"};
    m_strTitle = QObject::tr("选择文件");
}

QString FileLineEdit::selectFile(const QString &title)
{
    return openFileDialogWithTypes(title, m_fileTypes);
}

void FileLineEdit::setFileLineEditType(const FileLineEditType &type)
{
    switch (type) {
    case FileLineEditType::Image:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.png", "*.jpg", "*.bmp"};
        m_strTitle = QObject::tr("选择图片文件");
        break;
    case FileLineEditType::Text:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.txt", "*.md", "*.doc"};
        m_strTitle = QObject::tr("选择文本文件");
        break;
    case FileLineEditType::Binary:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.dat"};
        m_strTitle = QObject::tr("选择二进制文件");
        break;
    case FileLineEditType::Music:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.wav", "*.mp3"};
        m_strTitle = QObject::tr("选择音乐文件");
        break;
    case FileLineEditType::Program:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.exe"};
        m_strTitle = QObject::tr("选择程序文件");
        break;
    default:
        m_fileTypes.clear();
        m_fileTypes = QStringList{"*.*"};
        m_strTitle = QObject::tr("选择文件");
        break;
    }
}

QString FileLineEdit::getFilePathString()
{
    return m_strFilePath;
}

void FileLineEdit::mouseDoubleClickEvent(QMouseEvent *event)
{
    // 调用父类处理其他双击事件
    QLineEdit::mouseDoubleClickEvent(event);

    // 打开文件选择对话框
    QString filePath =  openFileDialogWithTypes(m_strTitle, m_fileTypes);

    // 如果用户选择了文件，更新QLineEdit的文本
    if (!filePath.isEmpty()) {
        m_strFilePath = filePath;
        setText(filePath);
    }
}

QString FileLineEdit::openFileDialogWithTypes(const QString &title, const QStringList &fileTypes)
{
    // 构造文件过滤器字符串
    QString filter = createFileFilter(fileTypes);

    // 打开文件选择对话框
    return QFileDialog::getOpenFileName(this, title, "", filter);
}

QString FileLineEdit::createFileFilter(const QStringList &fileTypes)
{
    QString filter;
    for (const QString &fileType : fileTypes) {
        filter += tr("文件类型 (%1);;").arg(fileType);
    }
    //filter += tr("所有文件 (*)");  // 加上“所有文件”选项
    return filter;
}

